#include "FormatConvert.h"


bool FormatConvert::YUV420ToYUV(ifstream &fin, Mat &imgYUV)
{
	unsigned int width = imgYUV.cols;
	unsigned int height = imgYUV.rows;
	char *pY = new char[width*height];
	char *pU = new char[width*height>>2];
	char *pV = new char[width*height>>2];
	if(pY == NULL || pU == NULL || pV == NULL)
	{
		cout<<"Fail to malloc memory!"<<endl;
		return false;
	}

	fin.read(pY, width*height);
	if(fin)
	{
		cout<<"Read Y successfully!"<<endl;
	}
	else
	{
		cout<<"Error: only "<<fin.gcount()<<"Y could be read!"<<endl;
		return false;
	}
	fin.read(pU, width*height>>2);
	if(fin)
	{
		cout<<"Read U successfully!"<<endl;
	}
	else
	{
		cout<<"Error: only "<<fin.gcount()<<"U could be read!"<<endl;
		return false;
	}
	fin.read(pV, width*height>>2);
	if(fin)
	{
		cout<<"Read V successfully!"<<endl;
	}
	else
	{
		cout<<"Error: only "<<fin.gcount()<<"V could be read!"<<endl;
		return false;
	}
	Mat imgY(height, width, CV_8UC1, pY);
	Mat imgU(height/2, width/2, CV_8UC1, pU);
	Mat imgV(height/2, width/2, CV_8UC1, pV);
	Mat imgUU(height, width, CV_8UC1);
	Mat imgVV(height, width, CV_8UC1);

	resize(imgU, imgUU, Size(width, height));
	resize(imgV, imgVV, Size(width, height));
	Mat pYUV[3];
	pYUV[0] = imgY;
	pYUV[1] = imgUU;
	pYUV[2] = imgVV;
	//Mat img(height, width, CV_8UC3);
	merge(pYUV, 3, imgYUV);
	//cvtColor(img, imgRGB, CV_YCrCb2RGB);
	delete[] pY;
	delete[] pU;
	delete[] pV;
	fin.close();
	return true;
}

bool FormatConvert::YUV420ToYUV(char *path, Mat &imgYUV)
{

	unsigned int width = imgYUV.cols;
	unsigned int height = imgYUV.rows;
	ifstream fin;
	fin.open(path, ios_base::in | ios_base::binary);
	if(fin.fail())
	{
		cout<<"The file is error!"<<endl;
		return false;
	}
	return YUV420ToYUV(fin, imgYUV);
}

bool FormatConvert::YUV420ToRGB888(char *path, Mat &imgRGB)
{
	unsigned int width = imgRGB.cols;
	unsigned int height = imgRGB.rows;
	ifstream fin;
	fin.open(path, ios_base::in | ios_base::binary);
	if(fin.fail())
	{
		cout<<"The file is error!"<<endl;
		return false;
	}
	return YUV420ToRGB888(fin, imgRGB);	
}

bool FormatConvert::YUV420ToRGB888(ifstream &fin, Mat &imgRGB)
{
	Mat img(imgRGB.rows, imgRGB.cols, CV_8UC3);
	YUV420ToYUV(fin, img);
	cvtColor(img, imgRGB, CV_YCrCb2RGB);
	return true;
}